from django.shortcuts import render,redirect
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse
import time

def frontpage(request):
    return render(request,'frontpage.html')

def login(request):
    res = {}
    if request.method == "GET":
        return render(request, "login.html")
    elif request.method == "POST":
        username = request.POST.get("usernameIn")
        password = request.POST.get("passwordIn")
        print(username,password)
        user_obj = auth.authenticate(username=username, password=password)
        if user_obj is not None:
            request.session['user_id'] = user_obj.id
            return redirect('/funcpage/')
        else:
            res['message'] = "用户名或密码错误"
            return render(request, "login.html", res)
    

def register(request):
    res = {}
    try:
        if request.method == 'POST':
            # 从POST请求中获取用户名和密码
            username = request.POST.get('usernameIn')
            password = request.POST.get('passwordIn')
            confirm_password = request.POST.get('cpasswordIn')
            print(username,password,confirm_password)
            # 检查密码是否匹配
            if password != confirm_password:
                res['message'] = '密码不匹配'
                return render(request, 'register.html', res)

            # 检查用户名是否已经被注册
            if User.objects.filter(username=username).exists():
                res['message'] = '用户名已被注册'
                return render(request,  'register.html',res)

            # 创建用户账户
            user = User.objects.create_user(username=username, password=password)
            user.save()
            res['message'] = "您的账号已成功创建!,请点击“返回登陆系统”,3秒后将自动跳转登陆界面。"
            time.sleep(3)
            # 如果创建用户成功，重定向到登陆页面
            # return redirect('/login')
            return render(request,'login.html',res)
    except:
        res['message'] = "请输入账号密码！"
        return render(request,'register.html',res)
    
    # 如果是GET请求，返回注册页面
    return render(request, 'register.html')

